library(readstata13)
library(tidyverse)

rm(list=ls())

setwd("C:/Users/m1049/Dropbox/Wang_PB Replication/data")

df<-read.dta13("ignorance.dta")

df<-df %>% dplyr::select(federal_sales_wrong, 
                  statewide_sales_wrong  , 
                  hard_to_estimate,
                  tax_rate_answer_wrong,
                  answer_wrong) %>% 
          drop_na()
df<-df %>% mutate(hard_to_estimate=ifelse(hard_to_estimate>4, 2, 1))

out<-df %>%
  mutate(federal=as.factor(ifelse(federal_sales_wrong==1, "X | ?", "O")),
         sales=as.factor(ifelse(statewide_sales_wrong==1, "X | ?", "O")),
         estimate=recode_factor(hard_to_estimate, `1` = "Disagree", `2` = "Agree"),
         rate=as.factor(ifelse(tax_rate_answer_wrong==1, "X | ?", "O")),
         share=as.factor(ifelse(answer_wrong==1, "X | ?", "O"))) %>% 
  dplyr::select(federal, sales, estimate, rate, share)


names <- list("federal"="In the United States, does the federal government levy sales taxes?",
              "sales"="Does the state you live in levies statewide sales taxes?",
              "estimate"="It is very difficult to estimate how much sales taxes you pay.",
              "rate"="In your opinion, who pays the highest tax rate in sales taxes?",
              "share"="In your opinion, who pays the most sales taxes as a percentage of income?")

# make labeller function  
labeller_fun <-
  function(variable,value){
    return(str_wrap(names[value], width = 20))
  }

out1<-out %>%
  pivot_longer(everything(), names_to = "var", values_to = "val") 
  

out1<-out1 %>% group_by(var) 

out1$var<-as_factor(out1$var)


out1%>%
  count(val) %>%
  mutate(Label = n/sum(n), 1)  %>%
  ggplot(aes(x = val, y = n)) +
  geom_col() +
  facet_grid(.~var, scales = "free", labeller = labeller_fun)+
  xlab("") +
  ylab("Number of respondents") + 
  ylim(c(0, 800)) +
  geom_text(aes(label = scales::percent(Label, accuracy = 0.1)), vjust = -0.5, size = 5) +
  scale_fill_grey() + 
  scale_color_grey() +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 0, vjust=0.99, size = 12),
        axis.text.y = element_text(size = 12),
        axis.title = element_text(size = 12),
        strip.text.x = element_text(size = 12))

ggsave("fig1.pdf", width = 12, height = 8)
